const {
	Service
} = require('egg');
 
 
const {
	WechatyBuilder,
	ScanStatus
} = require("wechaty");
const qrcode = require("qrcode-terminal");
 
let ctx;
let wechaty;
let startStatus = false;
 
const onMessage = async (message) => {
	console.log(`收到消息: ${message}`);
	if (message.type() === wechaty.Message.Type.Text && !message.room()) {
		const userMsg = await message.text();
 
		try {
			let msgRecord = [{
				"role": "user",
				"content": userMsg
			}];
			let res = await ctx.service.ernie.sendMsg(msgRecord);
			if (res) {
				if (res.error_code) {
					message.say(JSON.stringify(res));
					console.log(`报错: ${JSON.stringify(res)}`);
				} else {
					if (res.result) {
						message.say(res.result);
						console.log(`回复: ${res.result}`);
					}
				}
			}
		} catch (error) {
			console.log(error);
			message.say(JSON.stringify(error));
		}
	}
};
 
const onLogout = (user) => {
	console.log(`用户 ${user} 退出成功`);
};
const onLogin = async (user) => {
	console.log(`用户 ${user} 登录成功`);
};
const onError = console.error;
const onScan = (code, status) => {
	// status: 2代表链接等待调用，3代表链接已打开，这个链接实际上是提供一个登录的二维码供扫描
	if (status === ScanStatus.Waiting) {
		// status: 2代表等待，3代表扫码完成
		qrcode.generate(code, {
			small: true
		}, console.log)
	}
};
 
class WechatService extends Service {
	async startBot() {
		console.log('===================WechatService startBot=====================');
		ctx = this.ctx;
		if (startStatus && wechaty) {
			if (wechaty.isLoggedIn) {
				await wechaty.logout();
			}
			await wechaty.stop();
			startStatus = false;
			wechaty = null;
		}
		wechaty = await WechatyBuilder.build();
		wechaty
			.on("scan", onScan)
			.on("login", onLogin)
			.on("logout", onLogout)
			.on("error", onError)
			.on("message", onMessage);
		await wechaty.start();
		startStatus = true;
	}
}
 
module.exports = WechatService;